package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author zhangyx
 * @desc JWT工具类
 * @date 2020/8/10 15:32
 **/
public class JWTUtils {

    private static final String SIGN = "DKFDKSFJ1231@#!"; //定义密钥，自定义生成

    /**
     * 生成token header.payload.signature
     */
    public static String getToken(Map<String,String> map){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,7); //设置7天过期
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v) ->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    /**
     * 验证token合法性，如果不合法就会报错
     */
    public static void verifyToken(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token信息
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return decodedJWT;
    }
}
